package com.chenxinzhimusic.service

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Build
import androidx.annotation.OptIn
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.session.MediaController
import androidx.media3.session.MediaSession
import androidx.media3.session.MediaSessionService
import com.chenxinzhimusic.MainActivity
import com.chenxinzhimusic.api.Api
import com.chenxinzhimusic.viewmodel.MusicInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit


class MusicService : MediaSessionService() {
    companion object {

        var controller: MediaController? by mutableStateOf(null)
        fun playList(
            musicInfo: MusicInfo,
            musicInfoList: List<MusicInfo>,
            isPlay: Boolean = true
        ) {
            val list: List<MediaItem>
            val startIndex: Int
            runBlocking {
                withContext(Dispatchers.IO) {
                    list = musicInfoList.map {
                        MediaItem.Builder()
                            .setUri(it.musicId.let {
                                Api.getMusicUri(it)
                            })
                            .setMediaMetadata(
                                MediaMetadata.Builder()
                                    .setArtist(it.artist)
                                    .setTitle(it.title)
                                    .setArtworkUri(it.picUrl.toUri())
                                    .setAlbumTitle(it.album)
                                    .setAlbumArtist(it.artist)
                                    .build()
                            )
                            .setMediaId(it.musicId)
                            .build()
                    }
                    startIndex = musicInfoList.map { it.musicId }.indexOf(musicInfo.musicId)
                }
                controller?.setMediaItems(
                    list, startIndex,
                    musicInfo.position.seconds.toLong(DurationUnit.MILLISECONDS)
                )
                controller?.prepare()
                if (isPlay) {
                    controller?.play()
                }
            }


        }


    }

    private var player: ExoPlayer? = null
    private var mediaSession: MediaSession? = null

    @OptIn(UnstableApi::class)
    override fun onCreate() {
        super.onCreate()

        // 初始化播放器
        player = ExoPlayer.Builder(this)
            .setAudioAttributes(
                AudioAttributes.Builder()
                    .setUsage(C.USAGE_MEDIA)
                    .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC)
                    .build(), true
            )
            .setMediaSourceFactory(
                DefaultMediaSourceFactory(ResolvingDataSource.Factory(DefaultHttpDataSource.Factory()) {
                    runBlocking { it.withUri((Api.getMusicUrl(it.uri)?.data?.url ?: "").toUri()) }
                })
            )
            .setMaxSeekToPreviousPositionMs(Long.MAX_VALUE)
            .build()
        // 构建 MediaSession

        // 1. 创建一个 Intent，指向你希望打开的 Activity
        val sessionActivityIntent = Intent(this, MainActivity::class.java)
        // 如果你的 Activity 位于不同的 Gradle 模块，确保 Intent 能够正确解析。
        // 添加 FLAG_ACTIVITY_NEW_TASK 和 FLAG_ACTIVITY_CLEAR_TASK 可以确保当应用从通知启动时，
        // 创建一个新的任务栈，并清除该任务栈中的所有其他 Activity，从而提供清晰的用户导航体验。
        sessionActivityIntent.flags =
            Intent.FLAG_ACTIVITY_SINGLE_TOP
        // 2. 创建 PendingIntent
        // 使用 PendingIntent.getActivity() 来获取一个 PendingIntent，用于启动 Activity
        // FLAG_IMMUTABLE 是必需的，推荐使用 FLAG_UPDATE_CURRENT 来更新现有的 PendingIntent
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,  // 请求码，通常为0，但如果你有多个 PendingIntent，可以使用不同的值
            sessionActivityIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )
        player?.let {
            mediaSession = MediaSession.Builder(this, it)
                .setSessionActivity(pendingIntent)
                .build()
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "music_channel"
            val channelName = "音乐播放"
            val channel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_DEFAULT // 保证能显示
            )
            channel.description = "用于音乐播放的前台通知"
            channel.setShowBadge(false)

            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
        startForeground(
            100, NotificationCompat.Builder(this, "music_channel")
                .build()
        )
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? {
        return mediaSession
    }


    override fun onDestroy() {
        player?.stop()
        player?.release()
        player = null
        mediaSession?.release()
        mediaSession = null
        super.onDestroy()
    }
}
